#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/5/26 13:55
# @Author : 闫峰
# @File    : auth.py
import base64

from common.baserequest import Base_request
from common.setting import ensure_path_sep
from utils.mysqlUtils.db_pool import Database


class UtilsL:
    znkd_database_prod_db = Database(ensure_path_sep("\\config\\znkd_mysql_config.yaml"), "znkd_database_prod")

    def base64_to(self, OrderSourceId):
        sql1 = "SELECT CertIdAccessKeyId,UserTokenSecretAccessKey from sys_ordersource_authorization WHERE CustomerId=1 AND OrderSourceId=%s and IsActive=1"
        res1 = self.znkd_database_prod_db.fetch_all(sql1, (OrderSourceId,))
        key_str = res1[0].get('CertIdAccessKeyId') +":"+ res1[0].get('UserTokenSecretAccessKey')
        key_bytes = key_str.encode('utf-8')  # 将字符串转化为 bytes 类型
        base64_str = base64.b64encode(key_bytes).decode('ascii')  # 使用 Base64 编码将 bytes 转化为 Base64 编码字符串
        return "Basic " + base64_str

    def get_token(self, OrderSourceId):
        url = "https://marketplace.walmartapis.com/v3/token"
        Authorization = self.base64_to(OrderSourceId)
        headers = {
            "WM_QOS.CORRELATION_ID": "Irobotbox",
            "WM_SVC.NAME": "Walmart Marketplace",
            "Accept": "application/json",
            "ContentType": "application/json",
            "Authorization": Authorization
        }
        data = {
            "grant_type": "client_credentials"
        }
        res = Base_request().post_data(url,headers,data)
        return res.get("access_token")


if __name__ == '__main__':
    print(UtilsL().get_token(12816))
